<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select v-model="listQuery.namespace" placeholder="namespace" clearable class="filter-item" @change="handleFilter">
        <el-option v-for="item in namespaceList" :key="item.name" :label="item.name" :value="item.name" />
      </el-select>
      <el-button type="primary" @click="handleAddRole">Add Service</el-button>
    </div>

    <el-table :data="serviceList" style="width: 100%;margin-top:30px;" border>
      <el-table-column align="header-center" label="Service Name">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="Namespace">
        <template slot-scope="scope">
          {{ scope.row.namespace }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="Type">
        <template slot-scope="scope">
          {{ scope.row.type }}
        </template>
      </el-table-column>
      <el-table-column align="header-center" label="IP">
        <template slot-scope="scope">
          {{ scope.row.cluster_ip }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="Operations">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope)">查看</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'Edit Role':'New Role'">
      <el-form :model="role" label-width="80px" label-position="left">
        <el-form-item v-show="dialogType==='new'" label="Yaml">
          <el-input
            v-model="role.service"
            :autosize="{ minRows: 10, maxRows: 20}"
            type="textarea"
            placeholder="Yaml"
          />
        </el-form-item>
        <el-form-item v-show="dialogType==='edit'" label="Name">
          <el-input v-model="role.name" placeholder="Name" />
        </el-form-item>
        <el-form-item v-show="dialogType==='edit'" label="Json">
          <div class="editor-container">
            <json-editor ref="jsonEditor" v-model="rolejson" />
          </div>
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">Cancel</el-button>
        <el-button v-show="dialogType==='new'" type="primary" @click="confirmRole">Confirm</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import path from 'path'
import { deepClone } from '@/utils'
import { updateRole } from '@/api/role'
import { getServices, getNamespaces, createService, deleteService } from '@/api/kube'
import JsonEditor from '@/components/JsonEditor'

const defaultRole = {
  namespace: 'default',
  service: ''
}

export default {
  components: {
    JsonEditor
  },
  data() {
    return {
      role: Object.assign({}, defaultRole),
      routes: [],
      rolesList: [],
      dialogVisible: false,
      dialogType: 'new',
      checkStrictly: false,
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      serviceList: [],
      namespaceList: [],
      rolejson: {},
      listQuery: {
        namespace: 'default'
      }
    }
  },
  computed: {
    routesData() {
      return this.routes
    }
  },
  created() {
    this.getServiceList()
    this.getNamespaceList()
  },
  methods: {
    async getServiceList() {
      const res = await getServices(this.listQuery)
      this.serviceList = res.data.list
      console.log(res.data.list)
    },
    async getNamespaceList() {
      const res = await getNamespaces()
      this.namespaceList = res.data.list
      console.log(res.data.list)
    },
    handleFilter() {
      this.getServiceList()
    },
    handleAddRole() {
      this.role = Object.assign({}, defaultRole)
      this.dialogType = 'new'
      this.dialogVisible = true
      this.role.namespace = this.listQuery.namespace
    },
    handleEdit(scope) {
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.checkStrictly = true
      this.role = deepClone(scope.row)
      this.rolejson = this.role
    },
    handleDelete({ $index, row }) {
      this.$confirm('Confirm to remove the role?', 'Warning', {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      })
        .then(async() => {
          await deleteService({ name: row.name, namespace: row.namespace })
          this.rolesList.splice($index, 1)
          this.$message({
            type: 'success',
            message: 'Delete succed!'
          })
          this.getServiceList()
        })
        .catch(err => { console.error(err) })
    },
    generateTree(routes, basePath = '/', checkedKeys) {
      const res = []

      for (const route of routes) {
        const routePath = path.resolve(basePath, route.path)

        // recursive child routes
        if (route.children) {
          route.children = this.generateTree(route.children, routePath, checkedKeys)
        }

        if (checkedKeys.includes(routePath) || (route.children && route.children.length >= 1)) {
          res.push(route)
        }
      }
      return res
    },
    async confirmRole() {
      const isEdit = this.dialogType === 'edit'

      if (isEdit) {
        await updateRole(this.role.key, this.role)
        for (let index = 0; index < this.rolesList.length; index++) {
          if (this.rolesList[index].key === this.role.key) {
            this.rolesList.splice(index, 1, Object.assign({}, this.role))
            break
          }
        }
      } else {
        await createService(this.role)
        this.rolesList.push(this.role)
      }

      this.dialogVisible = false
      this.getServiceList()
      this.$notify({
        title: 'Success',
        dangerouslyUseHTMLString: true,
        message: `success`,
        type: 'success'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .roles-table {
    margin-top: 30px;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
}
.editor-container{
  position: relative;
  height: 100%;
}
</style>
